var mongoose = require('mongoose');
const Product = require('../models/product.model');

// 新增
exports.create = function(req, res, next) {
    const product = new Product(req.body);
    product.save().then((data) => {
        res.json(data);
    });
};

// 修改
exports.update = function(req, res, next) {
    const id = req.params.id;
    Product.findByIdAndUpdate(id, { $set: req.body }, { new: false }).then(data => {
        res.json(data);
        // 这里返回的数据是修改之前的数据，不是修改之后的数据
    });
};

// 删除
exports.remove = function(req, res, next) {
    const id = req.params.id;
    Product.findByIdAndDelete(id, (err, data) => {
        res.json(data);
    });
};

// 查询
exports.list = function(req, res, next) {
    var page = req.body.page ? req.body.page : 1,
        rows = req.body.rows ? req.body.rows : 5,
        queryCondition = {}; // 查询条件
        
    if (req.body.name && req.body.name.trim().length > 0) {
        name = req.body.name; // 将获取的名字赋给name
        var str = '(.*)' + name + '(.*)';
        queryCondition = {
            "productID": new RegExp(str)
        };
    } else {
        //显示全部数据
        name = req.body.name;
        queryCondition = {
            "productID": new RegExp(name, 'i')
        }
    }
    if(req.body.tag){
    	var someelse=req.body.tag.split(',').join('|');
	    var myReg=new RegExp(someelse,'i');
    }
    

    Product.paginate(queryCondition, { page: +page, limit: +rows }, function(err, result) {
        result.rows = result.docs;
        delete result.docs;
        res.json(result);
    });
};

// 查找单条数据
exports.getData = function(req, res, next) {
    var id = req.params.id;
    Product.findById(id).then(data => {
        res.json(data);
    });
};

// 批量删除
exports.removes = function(req, res, next) {
    var ids = req.body.ids.split(',');
    if (ids.length > 0) {
        Product.remove({ _id: { $in: ids } }).then(data => {
            res.json({
                'message': 'delete ok',
                status: 200
            });
        });
    };
};